import {redGetCode, reqLogout, reqUserInfo, reqUserLogin, reqUserRegister} from "../../api";


export default ({
    namespaced: true,
    state: {
        code: '',
        // token: '',
        userInfo: {}
    },
    mutations: {
        GETCODE(state, value) {
            state.code = value
        },
        USERLOGIN(state, value) {
            // state.token = value
            localStorage.setItem("TOKEN", value)
        },
        GETUSERINFO(state, value) {
            state.userInfo = value
        },
        CLEARUSERINFO(state) {
            // 把仓库中的用户信息清除
            state.userInfo = {}
            // 把localStorage中的token清除
            localStorage.removeItem("TOKEN")
        }
    },
    actions: {
        // 获取验证码
        async getCode({commit}, phone) {
            let result = await redGetCode(phone)
            // console.log(result)
            commit('GETCODE', result.data)
        },

        //用户注册
        async userRegister({commit}, userParams) {
            let result = await reqUserRegister(userParams);
            console.log('注册结果:' + result)
            if (result.code == 200) {
                return 'success';
            } else {
                return Promise.reject(new Error('注册失败！'))
            }
        },

        // 用户登陆【 服务器返回令牌：token 】
        async userLogin({commit}, loginParams) {
            let result = await reqUserLogin(loginParams);
            // console.log(result)
            if (result.code == 200) {
                commit('USERLOGIN', result.data.token);
                return "success"
            } else {
                return Promise.reject(new Error("faile"))
            }
        },

        // 获取用户信息
        async getUserInfo({commit}) {
            let result = await reqUserInfo();
            // console.log(result)
            if (result.code == 200) {
                commit('GETUSERINFO', result.data)
                return "success"
            } else {
                return Promise.reject(new Error('faile'))
            }
        },

        // 退出登陆
        async userLogout({commit}) {
            // 向服务器发送一次请求，清除token
            let result = await reqLogout()
            if (result.code == 200) {
                commit('CLEARUSERINFO')
            }
        }
    },
    getters: {}

})